#include "recbox.h"
#include "ui_recbox.h"

recBox::recBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::recBox),
    row(1),col(4),currentIndex(0)
{
    ui->setupUi(this);
}

recBox::~recBox()
{
    delete ui;
}

void recBox::initRecBoxUi(QJsonArray data, int row)
{
    if(row==2)
    {
        this->row=row;
        this->col=8;
    }
    else
    {
        ui->recListDown->hide();
    }
    this->imageList=data;
    this->currentIndex=0;
    this->count=imageList.size()/col;
    this->createRecItem();

}

void recBox::createRecItem()
{
    QList<recBoxItem*> recUpList = ui->recListUp->findChildren<recBoxItem*>();
    for(auto e:recUpList)
    {
        ui->recListUpHLayout->removeWidget(e);
        delete e;
    }
    QList<recBoxItem*> recDownList = ui->recListDown->findChildren<recBoxItem*>();
    for(auto e:recDownList)
    {
        ui->recListDownHLayout->removeWidget(e);
        delete e;
    }
    for(int i=0;i<this->col;i++)
    {
       recBoxItem *item=new recBoxItem();
       QJsonObject obj;
       if(i+this->col*this->currentIndex<this->imageList.size())
           obj=imageList[i+col*currentIndex].toObject();
       item->setRecText(obj.value("text").toString());
       item->setRecImage(obj.value("path").toString());

       if(i>=col/2&&row==2)
       {
           //ui->recListUpHLayout->addWidget(item);
           ui->recListDownHLayout->addWidget(item);
           //qDebug()<<"down ";
       }
       else
       {
           ui->recListUpHLayout->addWidget(item);
           //qDebug()<<"up ";
       }
    }
}

void recBox::on_btUp_clicked()
{
    this->currentIndex--;
    if(this->currentIndex<0)
        this->currentIndex=this->count-1;
    this->createRecItem();
}

void recBox::on_btDown_clicked()
{
    this->currentIndex++;
    if(this->currentIndex>=this->count)
        this->currentIndex=0;
    this->createRecItem();
}
